import _ from 'lodash';
import { message, Select } from 'antd';
import { NAME_SPACE, SearchParams, AddForm, Default_Columns } from '../components/CollectionObjManage/config';
import { pagingQueryCollectorObject, insertCollectorObject, deleteCollectorObject, updateCollectorObject, findOneCollectorObject } from '../services/collectionObjManage';
import moment from 'moment';

// 更新编辑
const  handleEditItem = (columns, editItem) => {
  let newItem = {};
  columns.map((item) => {
      newItem[item] = editItem[item];
  });
  return newItem;
} 

export default {
  namespace: NAME_SPACE,
  state: {
    loading: false,
    pageNo: 1,
    pageSize: 20,
    total: 0,
    searchParams: {...SearchParams},
    oldSearchParams: {...SearchParams},
    selectedRowKeys: [],
    dataList: [],
    // 详情可见
    detailsModelVisable: false,
    details: {},
    // 添加可见
    addModelVisable: false,
    addForm: {...AddForm},
    default_columns: [...Default_Columns],
    addLoading: false,
    // id
    modifyId: '',
    // 地图可见
    mapVisable: false,
    mapCenter: [116.40, 39.90],
    points: [],
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({pathname, query}) => {
        if(pathname == '/collectionObjManage'){
          dispatch({
            type:'init',
            payload:{}
          });
        }
      });
    },
  },
  effects: {
    *init({payload},{select, put, call}){
      yield put({
        type: 'getList',
        payload: {type: 'search'}
      })
    },
    *getList({payload},{select, put, call}){
      let {type: searchType, delNum} = payload;
      let {searchParams, oldSearchParams, total, pageSize, pageNo} = yield select(state => state[NAME_SPACE]);
      let newPageNo = 1, newPageSize = 20;
      switch (searchType) {
        case "search":
            oldSearchParams = Object.assign({}, searchParams);
            break;
        case "page":
            newPageNo = pageNo;
            newPageSize = pageSize;
        break;
            case "del":
            if (total===1 || (total-(pageNo)*pageSize - delNum)>0) {
                newPageNo = pageNo - 1 ;
            }else{
                newPageNo = pageNo ;
            }
            break;
        default :
            break;
      }
      yield put({
        type: 'updateState',
        payload: {
          loading: true
        }
      })
      const result = yield call(pagingQueryCollectorObject, {
        ...oldSearchParams,
        rows: newPageSize,
        page: newPageNo,
      })
      if(result.rc == 0){
        yield put({
          type: 'updateState',
          payload: {
            dataList: result.ret.items,
            total: result.ret.count,
            pageNo: newPageNo,
            pageSize: newPageSize,
            loading: false,
          }
        })
      }else{
        message.error('数据加载错误')
        yield put({
          type: 'updateState',
          payload: {
            dataList: [],
            total: 0,
            pageNo: 1,
            pageSize: 0,
            loading: false,
          }
        })
      }
    },
    *getDetail({payload},{select, put, call}){
      const {type, id} = payload
      const result = yield call(findOneCollectorObject, {hospitalId:id});
      if (result.rc == 0) {
          // 查看详情
          if (type == "view") {
              yield put({
                  type: "updateState",
                  payload: {
                      detailsModelVisable:true,
                      details: {
                          ...result.ret,
                      },

                  }
              });
          } else if (type == "modify"){
              // 加载修改数据
              yield put({
                  type: "updateState",
                  payload: {
                      addForm: {
                          ...result.ret,
                      },
                      // 记录修改数据id
                      modifyId:id,
                      // 显示修改弹窗
                      addModelVisable:true,
                  }
              });
          }
      }else{
          message.error('查询失败');
      }

    },
    *add({payload},{select, put, call}){
      const { addForm } = yield select(state => state[NAME_SPACE]);
      const result = yield call(insertCollectorObject, {...addForm})
      if( result.rc == 0 ){
        message.success('新增成功')
        yield put({
          type: 'getList',
          payload: {type: 'search', addModelVisable: false}
        })
      }else{
        message.error('新增失败')
      }
    },
    *_modify({payload},{select, put, call}){
      const { addForm, modifyId, default_columns } = yield select(state => state[NAME_SPACE]);
      yield put({
        type: "updateState",
        payload: {addLoading: true}
      });
      const result = yield call(updateCollectorObject, handleEditItem(default_columns, {...addForm, hospitalId: modifyId}))
      if(result.rc == 0){
        message.success('修改成功')
        yield put({
          type: 'getList',
          payload: {type: 'page'}
        })
      }else{
        message.error('修改失败')
      }
      yield put ({
        type: "updateState",
        payload: {addLoading: false, addModelVisable: false}
      })
    },
    *_delete({payload},{select, put, call}){
      yield put({
        type: "updateState",
        payload: {loading: true}
      });
      let {selectedRowKeys} = payload;
      let result = yield call(deleteCollectorObject,{hospitalId:selectedRowKeys.join(',')});
        if (result.rc == 0) {
            yield put({
                type: "getList",
                payload: {
                    type: "del",
                    delNum: selectedRowKeys.length,
                }
            });
            message.success('删除成功');
        }else{
            message.error('删除失败');
        }
      yield put({
          type: "updateState",
          payload: {
              loading: false,
          }
      });
    },
  },
  reducers:{
    updateState(state, { payload }) {
      return { ...state, ...payload };
    },
    updateSubState(state, { payload }) {
        let { data, sub } = payload;
        return {
            ...state,
            [sub]: {
                ...state[sub],
                ...data,
            }
        }
    },
  },
}